
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>

#include "./include/menu.h" 
#include "./include/serial_test.h" 
#include "./include/can_test.h" 
#include "./include/io_test.h" 
#include "./include/protocol.h"
#include "./include/tcp_sxx.h"
#include "./include/test_hardware.h"
char    ip_addr[16] = {0};
int     tcp_port = 0;


int tcpClient() 
{
    int choice;
    int sock = 0;
    
    struct sockaddr_in serv_addr;
    unsigned char buffer[BUFFER_SIZE] = {0};

    
    choice_target( ip_addr );
    
    /* 1. 创建socket */
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("套接字创建错误");
        return -1;
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(tcp_port);

    /* 2. 转换IP地址 */
    if (inet_pton(AF_INET, ip_addr, &serv_addr.sin_addr) <= 0) {
        perror("无效的IP地址");
        return -1;
    }

    /* 3. 连接服务器 */
    if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("连接失败");
        return -1;
    }
    
    int flags = fcntl(sock, 3, 0);
    fcntl(sock, 4, flags | 04000); // 设置非阻塞

    printf("[126z测试工装] 连接到服务器\n");
    test_start_bit(sock,buffer);
    printf("等待产品端开启任务!\n");
    recv_tcp_data_discard( sock, 8 );
    /* 4. 发送和接收数据 */
    while (1) 
    {
        
        show_menu();  // 显示菜单
        wait_scanf( sock );
        if (scanf("%d", &choice) != 1) {
            // 错误输入处理
            printf("无效的输入，请输入数字\n");
            // 清除输入缓冲区
            while(getchar() != '\n');
            continue;
        }
        // 正常处理choice
        printf("您选择了: %d\n", choice);
        // 处理用户选择的选项
        handle_choice( choice,sock, buffer);

        // 退出程序选项
        if (choice == 8) 
        {
            break ;
        }
        recv_tcp_data_discard( sock, 1 );
    }

    close(sock);
    return 0;
}
